﻿using AduSkin.Controls.Metro;
using HsServerHa.Core.Http;
using HsServerHa.Entity.Models;
using HsServerHa.Utility.DataHelper;
using HsServerHa.Utility.HttpHelper;
using HsServerHa.Utility.NetWork;
using HsServerHa.Utility.SQLite;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Net.NetworkInformation;
using System.Net;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using HsServerHa.Core;
using Newtonsoft.Json;
using CommunityToolkit.Mvvm.Messaging.Messages;
using CommunityToolkit.Mvvm.Messaging;
using System.Threading;
using static System.Net.Mime.MediaTypeNames;

namespace HsServerHa.UserControls.Dialog
{
    /// <summary>
    /// UpdateMultipleCard.xaml 的交互逻辑
    /// </summary>
    public partial class UpdateMultipleCard : UserControl
    {
        public long Id { get; set; }
        public UpdateMultipleCard(long Id)
        {
            this.Id = Id;


            InitializeComponent();
            InitData().Wait();
        }

        private List<NetWorkCardInfoEntity> remoteList = new List<NetWorkCardInfoEntity>();
        MultipleNetworkCardManageEntity netWorkFirst = new MultipleNetworkCardManageEntity();
        public async Task InitData()
        {
            //var sql = $@"select * from MultipleNetworkCardManage where Id={this.Id} ";
            //var netWorkDt = DbHelperSQLite.Query(sql)?.Tables?[0];
            //var netWorkList = DataHelpers.ConvertToModel<MultipleNetworkCardManageEntity>(netWorkDt);
            var netWorkList = SQLiteHelper.Table<MultipleNetworkCardManageEntity>().Where(x => x.Id == this.Id).ToList();

            netWorkFirst = netWorkList.FirstOrDefault();

            var adapterList = NetWorkHelper.GetNetworkInfo();
            int index = 0;
            int SelectIndex = 0;
            foreach (var adapter in adapterList)
            {
                string Name = adapter.Name;
                ComboBoxItem cbi = new ComboBoxItem();
                cbi.Content = Name;
                CurrNetWorkName.Items.Add(cbi);
                if (Name == netWorkFirst?.NetworkCardName)
                {
                    SelectIndex = index;
                }
                index++;
            }
            CurrNetWorkName.SelectedIndex = SelectIndex;
            CurrIP.Text = netWorkFirst?.CurrIP;

            if (App.isMaster != null)
            {
                //var sqlMaster2 = "SELECT * FROM  MasterSlaveBind where 1=1";
                //var dtMaster2 = DbHelperSQLite.Query(sqlMaster2)?.Tables?[0];
                //var masterList = DataHelpers.ConvertToModel<MasterSlaveBindEntity>(dtMaster2);
                var masterList = SQLiteHelper.Table<MasterSlaveBindEntity>().ToList();
                var masterFirst = masterList.FirstOrDefault();
                var masterPath = "";
                if (masterFirst == null)
                {
                    AduMessageBoxs.Show("系统设置错误！");
                    return;
                }
                if (App.isMaster.Value)
                {
                    if (string.IsNullOrEmpty(masterFirst.SlaveIP))
                    {
                        AduMessageBoxs.Show("主从未联机，请检查后再设置！");
                        return;
                    }
                    masterPath = $"http://{masterFirst.SlaveIP}:{ConfigurationManager.AppSettings["HttpPort"]?.ToString() ?? "6601"}/";

                }
                else
                {
                    masterPath = $"http://{masterFirst.MasterIP}:{ConfigurationManager.AppSettings["HttpPort"]?.ToString() ?? "6601"}/";
                }

                //修改MAC地址

                //if (IsSyncMAC.IsChecked.Value)
                //{
                //    //更改网卡MAC地址，网卡状态为启用时才会生效
                //    if (PhysicalAddress.TryParse(MAC.Text, out PhysicalAddress? mac))
                //    {
                //        int setMacResult = NetWorkHelper.SetMacAddress(NetWorkHelper.adapter.Description, MAC.Text);
                //        if (setMacResult != 0)
                //        {
                //            //设置失败
                //            AduMessageBoxs.Show("设置MAC地址失败,请检查网卡是否为启用状态!");
                //        }
                //    }
                //    //同步远程网卡
                //    var postSetMACAddressResult = await HttpHelpers.PostToJson<HttpResponseResultModel<object>>($"{masterPath}{ConfigurationManager.AppSettings["postSetMACAddress"]?.ToString() ?? "postSetMACAddress"}", JsonConvert.SerializeObject(new SetMACAddressEntity() { CardName = RemoteNetWorkName.Text, MAC = MAC.Text }));
                //    if (postSetMACAddressResult == null || !postSetMACAddressResult.IsSuccess)
                //    {
                //        AduMessageBoxs.Show("同步远程网卡失败！");
                //    }

                //}

                var list = await HttpHelpers.Get<HttpResponseResultModel<List<NetWorkCardInfoEntity>>>($"{masterPath}{ConfigurationManager.AppSettings["getRemoteCardInfo"]?.ToString() ?? "getRemoteCardInfo"}");
                if (list == null || !list.IsSuccess)
                {
                    AduMessageBoxs.Show("主从未联机，请检查后再设置！");
                }
                if (list.BackResult == null || list.BackResult?.Count == 0)
                {
                    return;
                }
                remoteList = list?.BackResult ?? new List<NetWorkCardInfoEntity>();
                int index1 = 0;
                int SelectIndex1 = 0;
                foreach (var item in list?.BackResult)
                {
                    string Name = item.CardName;
                    ComboBoxItem cbi = new ComboBoxItem();
                    cbi.Content = Name;
                    RemoteNetWorkName.Items.Add(cbi);
                    if (item.IP == netWorkFirst.RemoteIP)
                    {
                        SelectIndex1 = index1;
                        this.RemoteNetWorkIP.Text = item.IP;
                    }
                    index1++;
                }
                RemoteNetWorkName.SelectedIndex = SelectIndex1;
            }
            this.RemoteNetWorkIP.Text = netWorkFirst?.RemoteIP;
            this.SubnetMask.Text = netWorkFirst?.SubnetMask;
            this.Gateway.Text = netWorkFirst?.Gateway;
            this.DNS1.Text = netWorkFirst?.DNS1;
            this.DNS2.Text = netWorkFirst?.DNS2;
            this.MAC.Text = netWorkFirst?.MAC;
            this.ReferIP.Text = netWorkFirst?.ReferIP;
            this.VirtuallyIP.Text = netWorkFirst?.VirtuallyIP;
            this.IsEnable.SelectedIndex = netWorkFirst?.IsEnable == "是" ? 0 : 1;
            this.IsSyncMAC.IsChecked = netWorkFirst?.IsSyncMAC;
            this.CurrentMAC.Text = netWorkFirst?.CurrentMAC;
            this.RemoteMAC.Text = netWorkFirst?.RemoteMAC;
        }

        private void RemoteNetWorkName_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            string content = RemoteNetWorkName.SelectedValue.ToString().Replace("System.Windows.Controls.ComboBoxItem: ", "");
            var first = remoteList.FirstOrDefault(x => x.CardName == content);
            this.RemoteNetWorkIP.Text = first?.IP.ToString() ?? "";
            this.RemoteMAC.Text = first?.RemoteMac.ToString() ?? "";            
            
        }

        private void CurrNetWorkName_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            string content = CurrNetWorkName.SelectedValue.ToString().Replace("System.Windows.Controls.ComboBoxItem: ", "");
            var adapter = NetWorkHelper.GetAdapterByName(content);
            if (adapter != null)
            {
                IPInterfaceProperties ip = adapter.GetIPProperties();
                UnicastIPAddressInformationCollection ipCollection = ip.UnicastAddresses;
                var index = 0;
                foreach (UnicastIPAddressInformation item in ipCollection)
                {
                    if (item.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
                    {
                        this.CurrIP.Text = item.Address.ToString();
                        this.SubnetMask.Text = item.IPv4Mask.ToString();
                    }
                }
                Gateway.Text = NetWorkHelper.GetGateWay(ip);
                if (ip.DnsAddresses.Count > 0)
                {
                    DNS1.Text = ip.DnsAddresses[0].ToString();
                    if (ip.DnsAddresses.Count > 1)
                    {
                        DNS2.Text = ip.DnsAddresses[1].ToString();
                    }
                    else
                    {
                        DNS2.Text = "";
                    }
                }
                else
                {
                    DNS1.Text = "";
                    DNS2.Text = "";
                }
                PhysicalAddress pa = adapter.GetPhysicalAddress();
                byte[] bytes = pa.GetAddressBytes();
                StringBuilder sb = new StringBuilder();
                for (int i = 0; i < bytes.Length; i++)
                {
                    sb.Append(bytes[i].ToString("X2"));
                    if (i != bytes.Length - 1)
                    {
                        sb.Append('-');
                    }
                }
                MAC.Text = sb.ToString();
                this.CurrentMAC.Text = sb.ToString();
            }
        }
        private string GetRandMac()
        {
            var random = new Random();
            var buffer = new byte[6];
            random.NextBytes(buffer);
            buffer[0] &= 0b11111110;
            buffer[0] |= 0b00000010;
            var result = string.Concat(buffer.Select(x => string.Format("{0}-", x.ToString("X2"))).ToArray());
            return result.TrimEnd('-');
        }
        private void btn_MacRand_Click(object sender, RoutedEventArgs e)
        {
            this.MAC.Text = GetRandMac();
        }
       
        private async void btn_Setting_Click(object sender, RoutedEventArgs e)
        {
            if (string.IsNullOrEmpty(CurrNetWorkName.SelectedValue?.ToString().Replace("System.Windows.Controls.ComboBoxItem: ", "")))
            {
                AduMessageBoxs.Show("当前网卡未设置！");
                return;
            }
            if (string.IsNullOrEmpty(RemoteNetWorkName.SelectedValue?.ToString().Replace("System.Windows.Controls.ComboBoxItem: ", "")))
            {
                AduMessageBoxs.Show("远程网卡未设置！");
                return;
            }
            if (string.IsNullOrEmpty(CurrIP.Text))
            {
                AduMessageBoxs.Show("当前网卡IP不能为空！");
                return;
            }
            if (string.IsNullOrEmpty(RemoteNetWorkIP.Text))
            {
                AduMessageBoxs.Show("当前网卡IP不能为空！");
                return;
            }
            if (!NetWorkHelper.ValidateMask(SubnetMask.Text))
            {
                AduMessageBoxs.Show("子网掩码格式不正确！");
                return;
            }
            if (!NetWorkHelper.ValidateIpAddress(CurrIP.Text))
            {
                AduMessageBoxs.Show("请输入正确的当前IP");
                return;
            }
            if (!NetWorkHelper.ValidateIpAddress(RemoteNetWorkIP.Text))
            {
                AduMessageBoxs.Show("请输入正确的远程IP");
                return;
            }

            if (!NetWorkHelper.ValidateIpAddress(ReferIP.Text))
            {
                AduMessageBoxs.Show("请输入正确的参考IP");
                return;
            }
            else
            {
                if (!NetWorkHelper.IsPingIP(ReferIP.Text))
                {
                    AduMessageBoxs.Show("请输入合法的参考IP");
                    return;
                }
            }
            if (!NetWorkHelper.ValidateIpAddress(VirtuallyIP.Text))
            {
                AduMessageBoxs.Show("请输入正确的虚拟IP");
                return;
            }
            if (!NetWorkHelper.ValidateIPIsWithNetworkSegment(CurrIP.Text, RemoteNetWorkIP.Text))
            {
                AduMessageBoxs.Show("当前IP和远程IP请选择同网段IP！");
                return;
            }
            if (!NetWorkHelper.ValidateIPIsWithNetworkSegment(CurrIP.Text, VirtuallyIP.Text))
            {
                AduMessageBoxs.Show("当前IP和虚拟IP请选择同网段IP！");
                return;
            }

            var paramStr = new MultipleNetworkCardManageEntity()
            {
                CurrIP = RemoteNetWorkIP.Text,
                NetworkCardName = RemoteNetWorkName.SelectedValue?.ToString().Replace("System.Windows.Controls.ComboBoxItem: ", ""),
                RemoteIP = CurrIP.Text,
                SubnetMask = SubnetMask.Text,
                Gateway = Gateway.Text,
                DNS1 = DNS1.Text,
                DNS2 = DNS2.Text,
                MAC = MAC.Text,
                VirtuallyIP = VirtuallyIP.Text,
                IsEnable = IsEnable.SelectedValue?.ToString().Replace("System.Windows.Controls.ComboBoxItem: ", ""),
                ReferIP = ReferIP.Text,
                IsMaster = App.isMaster.Value ? "否" : "是",
                ProgramKey = netWorkFirst.ProgramKey,
                CreateTime = DateTime.Now.ToString(),
                IsSyncMAC = IsSyncMAC.IsChecked.Value,
                CurrentMAC =CurrentMAC.Text,
                RemoteMAC = RemoteMAC.Text
            };
            if (App.isMaster != null)
            {
                //var sqlMaster2 = "SELECT * FROM  MasterSlaveBind where 1=1";
                //var dtMaster2 = DbHelperSQLite.Query(sqlMaster2)?.Tables?[0];
                //var masterList = DataHelpers.ConvertToModel<MasterSlaveBindEntity>(dtMaster2);
                var masterList = SQLiteHelper.Table<MasterSlaveBindEntity>().ToList();


                var masterFirst = masterList.FirstOrDefault();
                var masterPath = "";
                if (App.isMaster.Value)
                {
                    if (string.IsNullOrEmpty(masterFirst.SlaveIP))
                    {
                        AduMessageBoxs.Show("主从未联机，请检查后再设置！");
                        LoggerHelper.Warn("系统API异常，请检查后再设置！", "多网卡设置");
                        return;
                    }
                    masterPath = $"http://{masterFirst.SlaveIP}:{ConfigurationManager.AppSettings["HttpPort"]?.ToString() ?? "6601"}/";
                }
                else
                {
                    masterPath = $"http://{masterFirst.MasterIP}:{ConfigurationManager.AppSettings["HttpPort"]?.ToString() ?? "6601"}/";
                }

                var result = await HttpHelpers.PostToJson<HttpResponseResultModel<object>>($"{masterPath}{ConfigurationManager.AppSettings["UpdateMulttipRemoteCardInfo"]?.ToString() ?? "UpdateMulttipRemoteCardInfo"}", JsonConvert.SerializeObject(paramStr));
                if (result == null)
                {
                    AduMessageBoxs.Show("系统API异常，请检查后再设置！");
                    LoggerHelper.Warn("系统API异常，请检查后再设置！", "多网卡设置");
                    return;
                }

                if (result.IsSuccess)
                {
                    var i = SQLiteHelper.ExecuteSql($"update MultipleNetworkCardManage set CurrIP='{CurrIP.Text}',NetworkCardName='{CurrNetWorkName.Text}',RemoteIP='{RemoteNetWorkIP.Text}',SubnetMask='{paramStr.SubnetMask}',Gateway='{Gateway.Text}',DNS1='{paramStr.DNS1}',DNS2='{paramStr.DNS2}',MAC='{paramStr.MAC}',CurrentMAC='{paramStr.CurrentMAC}',RemoteMAC='{paramStr.RemoteMAC}',VirtuallyIP='{paramStr.VirtuallyIP}',ReferIP='{paramStr.ReferIP}',IsMaster='{(App.isMaster.Value ? "是" : "否")}',IsEnable='{paramStr.IsEnable}',IsSyncMAC={paramStr.IsSyncMAC} where ProgramKey='{paramStr.ProgramKey}' ");
                    if (i >= 0)
                    {
                        AduMessageBoxs.Show("设置成功！");
                        WeakReferenceMessenger.Default.Send(new ValueChangedMessage<string>("刷新多网卡数据"), "RefreshNetworkCard");
                        LoggerHelper.SetInfo($"修改成功->{JsonConvert.SerializeObject(paramStr)}", "多网卡设置");
                        var control = this.Parent as ContentControl;
                        Window win = Window.GetWindow(control);
                        var title = win?.Title;
                        if (title != null)
                        {
                            if (title != "HsServerHa")
                            {
                                win.Close();
                            }

                        }


                        //修改MAC地址

                        //if (IsSyncMAC.IsChecked.Value)
                        //{
                        //    //更改网卡MAC地址，网卡状态为启用时才会生效
                        //    if (PhysicalAddress.TryParse(MAC.Text, out PhysicalAddress? mac))
                        //    {
                        //        //更改主机MAC地址
                        //        masterPath = $"http://{masterFirst.MasterIP}:{ConfigurationManager.AppSettings["HttpPort"]?.ToString() ?? "6601"}/";
                        //        var currNetWorkName = NetWorkHelper.GetAdapterByName(CurrNetWorkName.Text);
                        //        var remoteNetWorkName = RemoteNetWorkName.Text;
                        //        string macAddress = MAC.Text;
                        //        Task.Run(async () => SetMacAddress(currNetWorkName.Description, remoteNetWorkName, macAddress, masterPath));
                        //    }

                        //}
                        return;
                    }
                    else
                    {
                        AduMessageBoxs.Show("设置失败！");
                        LoggerHelper.Error("修改多网卡-设置失败,本地修改失败！", "多网卡设置");
                    }
                }
                else
                {
                    AduMessageBoxs.Show("设置失败，请检查系统配置！");
                    LoggerHelper.Error("修改多网卡-设置失败，请检查系统配置！", "多网卡设置");
                    return;
                }
            }
            else
            {
                AduMessageBoxs.Show("系统异常，请检查后再设置！");
                LoggerHelper.Error("修改多网卡-系统异常，请检查后再设置！", "多网卡设置");
                return;
            }
        }
        //public async Task SetMacAddress(string Description, string remoteNetWorkName, string MacAddress, string masterPath)
        //{
        //    Thread.Sleep(5000);
        //    //同步远程网卡
        //    if (App.isMaster.Value)
        //    {
        //        Thread.Sleep(5000);
        //        int setMacResult = NetWorkHelper.SetMacAddress(Description, MacAddress);
        //        if (setMacResult != 0)
        //        {
        //            //设置失败
        //            AduMessageBoxs.Show("设置MAC地址失败,请检查网卡是否为启用状态!");
        //        }
        //        var postSetMACAddressResult = await HttpHelpers.PostToJson<HttpResponseResultModel<object>>($"{masterPath}{ConfigurationManager.AppSettings["postSetMACAddress"]?.ToString() ?? "postSetMACAddress"}", JsonConvert.SerializeObject(new SetMACAddressEntity() { CardName = remoteNetWorkName, MAC = MacAddress }));
        //        //if (postSetMACAddressResult == null || !postSetMACAddressResult.IsSuccess)
        //        //{
        //        //    AduMessageBoxs.Show("同步远程网卡失败！");
        //        //    return;
        //        //}
        //    }
        //}
    }
}
